package org.btik.light.mobile.ui.home;

import android.content.Context;
import android.widget.ArrayAdapter;
import androidx.fragment.app.FragmentManager;
import androidx.lifecycle.ViewModel;
import org.btik.light.meta.DevArea;
import org.btik.light.mobile.MainActivity;
import org.btik.light.mobile.R;
import org.btik.light.mobile.meta.DevPanelType;
import org.btik.light.mobile.meta.mo.DefaultDevMo;
import org.btik.light.mobile.meta.mo.DefaultDevMoFactory;
import org.btik.light.mobile.server.DevEventListener;
import org.btik.light.meta.DevMo;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class HomeViewModel extends ViewModel implements DevEventListener {

    private static DevListAdapter adapter;

    private static final List<DefaultDevMo> devs = new ArrayList<>();

    private static final Map<String, Integer> devPos = new HashMap<>();

    private FragmentManager fragmentManager;

    public HomeViewModel() {

    }


    public ArrayAdapter<DefaultDevMo> getAdapter() {
        return adapter;
    }

    public void initAdaptor(Context context) {
        if (adapter == null) {
            adapter = new DevListAdapter(context, R.layout.dev_item, devs);
        }
    }


    @Override
    public void onDevConnect(DevMo dev) {

        if (dev instanceof DefaultDevMo) {
            DefaultDevMo devMo = (DefaultDevMo) dev;
            devMo.setDevArea(DevArea.LOCAL);
            // 重复接入覆盖
            putDev(devMo);
        }
    }

    public void onDevSync(List<DefaultDevMo> devMos){
        for (DefaultDevMo devMo : devMos) {
            devMo.setDevArea(DevArea.CLOUD);
            DevPanelType panelType = DefaultDevMoFactory.getPanelType(devMo);
            devMo.setDevPanelType(panelType);
            putDev(devMo);
        }

    }

    private void putDev(DefaultDevMo devMo) {
        String sn = devMo.getSn();
        Integer pos = devPos.get(sn);
        if (pos != null) {
            DefaultDevMo oldMo = devs.get(pos);
            if (oldMo != null) {
                oldMo.setExtendedAttributes(devMo.getExtendedAttributes());
                return;
            }
        }
        MainActivity.runUIWorker(() -> {
            adapter.add(devMo);
            devPos.put(sn, devs.size() - 1);
        });
    }

    public void setFragmentManager(FragmentManager fragmentManager) {
        this.fragmentManager = fragmentManager;
    }

    public FragmentManager getFragmentManager() {
        return fragmentManager;
    }
}